﻿using System;
using System.Collections.Generic;
using System.Text;
using MES.DataGateway.StandardEntity;
using System.Xml;
using System.Windows.Forms;
using System.Data;
using MES.DataGateway.Common;
using System.Text.RegularExpressions;

namespace MES.DataGateway.SyncCommon
{
    public class AssistantClass
    {
        private ServiceEntity m_ServiceInfoEntity = null;
        private string m_DataFilePath = "";
        private string m_ProjectID = "";
        private string m_LibID = "";

        #region 属性
        public string ProjectID
        {
            get { return m_ProjectID; }
            set { m_ProjectID = value; }
        }

        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }

        public string LibID
        {
            get { return m_LibID; }
            set { m_LibID = value; }
        }

        public ServiceEntity ServiceInfoEntity
        {
            get { return m_ServiceInfoEntity; }
            set { m_ServiceInfoEntity = value; }
        }
        #endregion

        #region 导入数据文件
        public void LoadXmlData(TreeView trvMes, TreeView trvEnterprise)
        {
            string strFilter = string.Format("ProjectID='{0}' and libID='{1}'", m_ServiceInfoEntity.ProjectID, m_LibID);
            DataRow[] rows = m_ServiceInfoEntity.ServiceTable.Select(strFilter);

            CreateMesTemple(Application.StartupPath + "\\XML\\Template\\MES\\" + rows[0]["MesTemplate"].ToString().Trim(), trvMes);
            CreateEnterpriseDataSource(m_DataFilePath, trvEnterprise);
        }

        private void CreateEnterpriseDataSource(string strPath, TreeView trvEnterprise)
        {
            trvEnterprise.Nodes.Clear();
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strPath);

            XmlNode stu = myxml.DocumentElement;
            foreach (XmlNode node in stu.ChildNodes)
            {
                TreeNode childNodes = new TreeNode();
                childNodes.Text = node.Name;
                childNodes.Tag = node.InnerText;
                GetChildXmlNode(node, childNodes);
                trvEnterprise.Nodes.Add(childNodes);
            }
        }

        private void GetChildXmlNode(XmlNode nodes, TreeNode childTreeNode)
        {
            if (nodes.ChildNodes.Count == 0)
            {
                return;
            }
            else
            {
                foreach (XmlNode childNode in nodes.ChildNodes)
                {
                    TreeNode myNode = new TreeNode();
                    myNode.Text = childNode.Name;
                    myNode.Tag = childNode.InnerText;
                    GetChildXmlNode(childNode, myNode);
                    childTreeNode.Nodes.Add(myNode);
                }
            }
        }

        private void CreateMesTemple(string strFileName, TreeView trvMes)
        {
            trvMes.Nodes.Clear();
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strFileName);
            if (myxml.DocumentElement == null)
            {
                return;
            }
            XmlNode stu = myxml.DocumentElement;
            foreach (XmlNode node in stu.ChildNodes)
            {
                TreeNode childNodes = new TreeNode();
                childNodes.Text = node.Name;
                if (node.Attributes.GetNamedItem("Type") != null)
                {
                    childNodes.Tag = node.Attributes.GetNamedItem("Type").Value;
                }
                else
                {
                    childNodes.Tag = "";
                }
                GetMesChildXmlNode(node, childNodes);
                trvMes.Nodes.Add(childNodes);
            }
        }

        private void GetMesChildXmlNode(XmlNode nodes, TreeNode childTreeNode)
        {
            if (nodes.ChildNodes.Count == 0)
            {
                return;
            }
            else
            {
                foreach (XmlNode childNode in nodes.ChildNodes)
                {
                    TreeNode myNode = new TreeNode();
                    myNode.Text = childNode.Name;
                    if (childNode.Attributes.GetNamedItem("Type") != null)
                    {
                        myNode.Tag = childNode.Attributes.GetNamedItem("Type").Value;
                    }
                    else
                    {
                        myNode.Tag = "";
                    }
                    GetMesChildXmlNode(childNode, myNode);
                    childTreeNode.Nodes.Add(myNode);
                }
            }
        }
        #endregion

        #region 数据显示规则处理
        public string PatchName(string resourceName, string fullPatch, TreeView trvEnterprise)
        {
            string strTmpName = resourceName;
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and FileldName='{2}'", m_ServiceInfoEntity.ProjectID, m_LibID, fullPatch);
            DataRow[] mainRuleRows = m_ServiceInfoEntity.RuleTable.Select(strFilter); //数据处理规则

            if (mainRuleRows.Length == 0)
                return resourceName;

            string strUpTmp = "";
            string strDownTmp = "";

            strFilter = string.Format("RuleID='{0}'", mainRuleRows[0]["RuleID"].ToString().Trim());
            DataRow[] mainRuleDetailRows = m_ServiceInfoEntity.RuleDetailiTable.Select(strFilter, "JoinSeq asc");
            foreach (DataRow row in mainRuleDetailRows)
            {
                if (Convert.ToInt32(row["JoinPlace"]) == 0) //前置
                {
                    if (row["JoinType"].ToString().Trim() == "Object")
                    {
                        string strValue = GetMappingValueByPath(row["AssociateFiledName"].ToString().Trim(), trvEnterprise);

                        strUpTmp = strUpTmp + strValue + row["JoinSymbol"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "String")
                    {
                        strUpTmp = strUpTmp + row["AssociateFiledName"].ToString().Trim() + row["JoinSymbol"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "Date")
                    {
                        if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD")
                        {
                            strUpTmp = strUpTmp + DateTime.Today + row["JoinSymbol"].ToString().Trim();
                        }
                        else if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD HH:mm:ss")
                        {
                            strUpTmp = strUpTmp + DateTime.Now + row["JoinSymbol"].ToString().Trim();
                        }
                    }
                }
                else
                {
                    if (row["JoinType"].ToString().Trim() == "Object")
                    {
                        string strValue = GetMappingValueByPath(row["AssociateFiledName"].ToString().Trim(), trvEnterprise);

                        strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + strValue;
                    }
                    else if (row["JoinType"].ToString().Trim() == "String")
                    {
                        strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + row["AssociateFiledName"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "Date")
                    {
                        if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD")
                        {
                            strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + DateTime.Today;
                        }
                        else if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD HH:mm:ss")
                        {
                            strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + DateTime.Now;
                        }
                    }
                }
            }

            return strUpTmp + resourceName + strDownTmp;
        }

        public string PatchNameByCly(string resourceName, string fullPatch, int intIndex, TreeView trvEnterprise)
        {
            string strTmpName = resourceName;
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and FileldName='{2}'", m_ServiceInfoEntity.ProjectID, m_LibID, fullPatch);
            DataRow[] mainRuleRows = m_ServiceInfoEntity.RuleTable.Select(strFilter); //数据处理规则

            if (mainRuleRows.Length == 0)
                return resourceName;
            string strUpTmp = "";
            string strDownTmp = "";
            strFilter = string.Format("RuleID='{0}'", mainRuleRows[0]["RuleID"].ToString().Trim());
            DataRow[] mainRuleDetailRows = m_ServiceInfoEntity.RuleDetailiTable.Select(strFilter, "JoinSeq asc");
            foreach (DataRow row in mainRuleDetailRows)
            {
                if (Convert.ToInt32(row["JoinPlace"]) == 0) //前置
                {
                    if (row["JoinType"].ToString().Trim() == "Object")
                    {
                        string strValue = GetMappingValueByPathCly(row["AssociateFiledName"].ToString().Trim(), trvEnterprise, intIndex);

                        strUpTmp = strUpTmp + strValue + row["JoinSymbol"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "String")
                    {
                        strUpTmp = strUpTmp + row["AssociateFiledName"].ToString().Trim() + row["JoinSymbol"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "Date")
                    {
                        if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD")
                        {
                            strUpTmp = strUpTmp + DateTime.Today + row["JoinSymbol"].ToString().Trim();
                        }
                        else if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD HH:mm:ss")
                        {
                            strUpTmp = strUpTmp + DateTime.Now + row["JoinSymbol"].ToString().Trim();
                        }
                    }
                }
                else
                {
                    if (row["JoinType"].ToString().Trim() == "Object")
                    {
                        string strValue = GetMappingValueByPathCly(row["AssociateFiledName"].ToString().Trim(), trvEnterprise, intIndex);

                        strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + strValue;
                    }
                    else if (row["JoinType"].ToString().Trim() == "String")
                    {
                        strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + row["AssociateFiledName"].ToString().Trim();
                    }
                    else if (row["JoinType"].ToString().Trim() == "Date")
                    {
                        if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD")
                        {
                            strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + DateTime.Today;
                        }
                        else if (row["AssociateFiledName"].ToString().Trim() == "YYYY-MM-DD HH:mm:ss")
                        {
                            strDownTmp = strDownTmp + row["JoinSymbol"].ToString().Trim() + DateTime.Now;
                        }
                    }
                }
            }

            return strUpTmp + resourceName + strDownTmp;
        }
        #endregion

        #region 查找单节点映射值
        public string GetMappingValue(TreeNode node, TreeView trvEnterprise, ref string resourceWorkFlowName)
        {
            string strValue = "";
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ProjectID, m_LibID, node.FullPath);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记
            if (mappingRows.Length > 0)
            {//多个映射，多次获取直到取到值 yangsj 20180327
                for (int i = 0; i <= mappingRows.Length - 1; i++)
                {
                    strValue = SearchMappingValue(mappingRows[i]["EnterpriseFileld"].ToString().Trim(), trvEnterprise);
                    if (!string.IsNullOrWhiteSpace(strValue.Trim()))
                        break;
                }
                resourceWorkFlowName = strValue;
            }
            string strTmp = PatchName(strValue, node.FullPath, trvEnterprise);
            return strTmp;
        }
        /// <summary>
        /// 根据路径获取映射值 Yangsj 2018-4-13
        /// </summary>
        /// <param name="path"></param>
        /// <param name="trvEnterprise"></param>
        /// <returns></returns>
        private string GetMappingValueByPath(string path, TreeView trvEnterprise)
        {
            string strValue = "";
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ServiceInfoEntity.ProjectID, m_LibID, path);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记
            if (mappingRows.Length > 0)
            {//多个映射，多次获取直到取到值 yangsj 20180327
                for (int i = 0; i <= mappingRows.Length - 1; i++)
                {
                    strValue = SearchMappingValue(mappingRows[i]["EnterpriseFileld"].ToString().Trim(), trvEnterprise);
                    if (!string.IsNullOrWhiteSpace(strValue.Trim()))
                        break;
                }
            }
            return strValue;
        }
        /// <summary>
        /// 根据路径获取映射值 Yangsj 2018-4-13
        /// </summary>
        private string GetMappingValueByPathCly(string path, TreeView trvEnterprise, int intIndex)
        {
            string strValue = "";
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ServiceInfoEntity.ProjectID, m_LibID, path);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记

            for (int i = 0; i <= mappingRows.Length - 1; i++)
            {
                int intNumber = 0;
                CheckNodeCryNumber(mappingRows[i]["EnterpriseFileld"].ToString().Trim(), trvEnterprise, ref intNumber);
                if (intNumber > 1)
                {
                    strValue = GetCryValue(mappingRows[i]["EnterpriseFileld"].ToString().Trim(), intIndex, trvEnterprise);
                }
                else
                {
                    strValue = SearchMappingValue(mappingRows[i]["EnterpriseFileld"].ToString().Trim(), trvEnterprise);
                }
                if (!string.IsNullOrWhiteSpace(strValue.Trim()))
                    break;
            }
            return strValue;
        }
        #endregion

        #region 查找目标文件映射路径
        public string GetMappingPath(TreeNode node)
        {
            string strFilter = string.Format("projectID='{0}' and LibID='{1}' and mesFileld='{2}'", m_ProjectID, m_LibID, node.FullPath);
            DataRow[] mappingRows = m_ServiceInfoEntity.MappingTable.Select(strFilter); //映射条件登记
            if (mappingRows.Length > 0)
            {
                return mappingRows[0]["EnterpriseFileld"].ToString().Trim();
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 获取循环节点的循环次数
        public int GetCryNodeNumber(string nodeFullPath, TreeView trvEnterprise)
        {
            int intCryNumber = 0;
            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (node.FullPath == nodeFullPath)
                {
                    intCryNumber = intCryNumber + 1;
                }
                else
                {
                    GetCryChidlNodeNumber(nodeFullPath, node, ref intCryNumber);
                }
            }
            return intCryNumber;
        }

        private void GetCryChidlNodeNumber(string nodeFullPath, TreeNode childNodes, ref int intCryNumber)
        {
            foreach (TreeNode node in childNodes.Nodes)
            {
                if (node.FullPath == nodeFullPath)
                {
                    intCryNumber = intCryNumber + 1;
                }
                else
                {
                    GetCryChidlNodeNumber(nodeFullPath, node, ref intCryNumber);
                }
            }
        }
        #endregion

        #region 检查循环节点在目标文件中的循环次数
        public void CheckNodeCryNumber(string nodeFullPath, TreeView trvEnterprise, ref int intNumber)
        {
            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (nodeFullPath.ToLower().Contains(node.FullPath.ToLower()))
                {
                    if (node.FullPath == nodeFullPath)
                    {
                        intNumber = intNumber + 1;
                    }
                    else
                    {
                        CheckNodeCryNumberChild(nodeFullPath, node, ref intNumber);
                    }
                }
            }
        }

        private void CheckNodeCryNumberChild(string nodeFullPath, TreeNode childNodes, ref int intNumber)
        {
            string[] strs = nodeFullPath.Split('\\');

            if (childNodes.Nodes.Count == 0)
                return;

            if (childNodes.Level + 1 > strs.Length - 1)
                return;
            if (childNodes.Text != strs[childNodes.Level])
                return;
            if (childNodes.Level + 1 == strs.Length - 1)
            {
                //只要有相同的父节点就增加
                //foreach (TreeNode node in childNodes.Nodes)
                //{
                //    if (node.FullPath.ToLower() == nodeFullPath.ToLower()) //todo ltian 20150507
                //    {
                //            intNumber = intNumber + 1;
                //            break;
                //    }
                //}
                intNumber = intNumber + 1;
            }
            else
            {
                foreach (TreeNode node in childNodes.Nodes)
                {
                    CheckNodeCryNumberChild(nodeFullPath, node, ref intNumber);

                }
            }
        }

        #endregion

        #region 根据映射条件查找对应的值
        private string SearchMappingValue(string nodeFullPath, TreeView trvEnterprise)
        {
            string strRturnValue = "";
            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (node.FullPath.ToLower() == nodeFullPath.ToLower()) //todo litan 20150507
                {
                    if (node.Tag == null)
                    {
                        strRturnValue = "";
                        break;
                    }
                    else
                    {
                        strRturnValue = node.Tag.ToString().Trim();
                        break;
                    }
                }
                else
                {
                    strRturnValue = SearchChildMappingValue(nodeFullPath, node);
                    if (strRturnValue.Trim() != "")
                    {
                        break;
                    }
                }
            }
            return strRturnValue;
        }

        private string SearchChildMappingValue(string nodeFullPath, TreeNode childNodes)
        {
            string strRturnValue = "";
            foreach (TreeNode node in childNodes.Nodes)
            {
                if (node.FullPath.ToLower() == nodeFullPath.ToLower())
                {
                    if (node.Tag == null)
                    {
                        strRturnValue = "";
                        break;
                    }
                    else
                    {
                        strRturnValue = node.Tag.ToString().Trim();
                        break;
                    }
                }
                else
                {
                    strRturnValue = SearchChildMappingValue(nodeFullPath, node);
                    if (strRturnValue.Trim() != "")
                    {
                        break;
                    }
                }
            }
            return strRturnValue;
        }
        #endregion

        #region 循环取相关节点值
        public string GetCryValue(string resourceFullPath, int intIndex, TreeView trvEnterprise)
        {
            string strReturnValue = "";
            List<string> valueList = new List<string>();

            foreach (TreeNode node in trvEnterprise.Nodes)
            {
                if (resourceFullPath.ToLower().Contains(node.FullPath.ToLower()))
                {
                    if (node.FullPath == resourceFullPath)
                    {
                        string strNodeValue = "";
                        if (node.Tag != null)
                        {
                            strNodeValue = node.Tag.ToString().Trim();
                        }
                        valueList.Add(strNodeValue);
                    }
                    else
                    {
                        GetChildCryValue(resourceFullPath, node, valueList);
                    }
                }
            }

            for (int i = 0; i < valueList.Count; i++)
            {
                if (i == intIndex)
                {
                    strReturnValue = valueList[i];
                }
            }
            return strReturnValue;
        }

        private void GetChildCryValue(string resourceFullPath, TreeNode parentNode, List<string> valueList)
        {
            string[] strs = resourceFullPath.Split('\\');
            string strNodeValue = null;
            if (parentNode.Nodes.Count == 0)
                return;

            if (parentNode.Level + 1 > strs.Length - 1)
                return;
            if (parentNode.Text != strs[parentNode.Level])
                return;

            if (parentNode.Level + 1 == strs.Length - 1)
            {
                //只要有相同的父节点就增加
                foreach (TreeNode node in parentNode.Nodes)
                {
                    if (node.FullPath.ToLower() == resourceFullPath.ToLower()) //todo ltian 20150507
                    {
                        if (node.Tag != null)
                            strNodeValue = node.Tag.ToString().Trim();
                        else
                            strNodeValue = "";
                        valueList.Add(strNodeValue);
                        break;
                    }
                }
                if (strNodeValue == null)
                    valueList.Add("");
            }
            else
            {
                foreach (TreeNode node in parentNode.Nodes)
                {
                    GetChildCryValue(resourceFullPath, node, valueList);
                }
            }
        }
        #endregion

        #region 公差信息处理
        public string CheckDraw(string strResource)
        {
            DataSet gcSet = new DataSet();
            gcSet.ReadXml(Application.StartupPath + "\\XML\\GcInfo.xml");
            foreach (DataRow row in gcSet.Tables[0].Rows)
            {
                string TCMValue = row["TCM"].ToString().Trim();
                int intTmp = strResource.IndexOf(TCMValue);
                if (intTmp == -1)
                {
                    continue;
                }
                if (TCMValue == "<%RA>")
                {
                    strResource = strResource.Replace(TCMValue, "<Q></Q>");
                    strResource = DrawExImage(strResource, "<Q>", "</Q>");
                }
                else if (TCMValue == "<%RA")
                {
                    strResource = DrawExR(strResource, "<%RA", ">");
                }
                else if (TCMValue == "<H>")
                {
                    strResource = DrawExHL(strResource, "<H>", "</H>");
                }
                else if (TCMValue == "<L>")
                {
                    strResource = DrawExHL(strResource, "<L>", "</L>");
                }
                else if (TCMValue == "<T")
                {
                    strResource = DrawExImageT(strResource, "<T", ">");
                }
                else
                {
                    strResource = DrawEx(strResource, TCMValue);
                }

            }
            strResource = DrawExImage(strResource, "<&70><+>", "<+><&90>");
            strResource = strResource.Replace("<$s>", "°");
            return strResource;

        }

        public string SetFormatSpecInfo(string strValue)
        {
            DataSet gcSet = new DataSet();
            gcSet.ReadXml(Application.StartupPath + "\\XML\\GcInfo.xml");
            int isHave = 0;
            foreach (DataRow row in gcSet.Tables[0].Rows)
            {
                int intTmp = strValue.IndexOf(row["TCM"].ToString().Trim());
                if (intTmp != -1)
                {
                    isHave = 1;
                    break;
                }
            }

            if (isHave == 0)
            {
                return strValue;
            }
            string strDraw = CheckDraw(strValue);
            if (strDraw.Trim() != "")
            {
                strValue = "<Image>" + strDraw + "</Image>";
            }
            else
            {

                string strNewValue = ReplaceH(strValue, "<H>");
                strNewValue = ReplaceH(strNewValue, "<L>");
                string strTmp = "";
                if (strNewValue.IndexOf("<O>") != -1)
                {
                    strTmp = strNewValue.Replace("<O>", "<Image>φ");
                    int intIndex = 0;
                    for (int j = 0; j < strTmp.Length; j++)
                    {
                        if (strTmp[j] == 'φ')
                        {
                            intIndex = intIndex + 1;
                        }
                    }

                    int intIndexTmp1 = 0;
                    for (int j = 0; j < intIndex; j++)
                    {
                        for (int k = 0; k < strTmp.Length; k++)
                        {
                            if (strTmp[k] == 'φ')
                            {
                                if (intIndexTmp1 != j)
                                {
                                    intIndexTmp1 = intIndexTmp1 + 1;
                                    continue;
                                }

                                string strtmp1 = "";
                                string strtmp2 = "";

                                for (int h = k + 1; h < strTmp.Length; h++)
                                {
                                    if (strTmp[h] == '>')
                                    {
                                        strtmp1 = strTmp.Substring(0, h + 1) + "</Image>";
                                        if (h < strTmp.Length)
                                        {
                                            strtmp2 = strTmp.Substring(h + 1);
                                        }
                                        else
                                        {
                                            strtmp2 = " ";
                                        }
                                        break;
                                    }
                                }
                                if (strtmp1 != "" && strtmp2 != "")
                                {
                                    strTmp = strtmp1 + strtmp2;
                                }
                                else
                                {
                                    strTmp = strtmp1;
                                }
                                break;
                            }
                        }
                    }
                    strValue = strTmp;
                }
                else
                {
                    strValue = "<Image>" + strTmp + "</Image>";
                }
            }
            return strValue;
        }

        private string ReplaceH(string strResource, string strSearch)
        {

            if (strResource.IndexOf(strSearch) == -1)
            {
                return strResource;
            }

            string strTmp = strResource.Replace(strSearch, "$");
            string strTmp1 = "";

            string[] strArray = strTmp.Split('$');

            if (strArray.Length % 2 == 0)  //偶数个替换符
            {
                for (int j = 0; j < strArray.Length; j++)
                {
                    if (j % 2 != 0)
                    {
                        strTmp1 = strTmp1 + strArray[j] + "<H>";
                    }
                    else
                    {
                        strTmp1 = strTmp1 + strArray[j] + "</H>";
                    }
                }
            }
            else
            {
                for (int j = 0; j < strArray.Length; j++)
                {
                    if (j == strArray.Length - 1)
                    {
                        strTmp = strTmp + strArray[j];
                    }
                    else
                    {
                        if (j % 2 != 0)
                        {
                            strTmp1 = strTmp1 + strArray[j] + "<H>";
                        }
                        else
                        {
                            strTmp1 = strTmp1 + strArray[j] + "</H>";
                        }
                    }
                }
            }
            return strTmp1;
        }

        public string CheckDrawold(string strResource)
        {
            if (!strResource.Contains("<&70><+>"))
            {
                return CheckDrawHelp(strResource);
            }

            strResource = strResource.Replace("<&70><+>", "<Image><&70><+>");
            strResource = strResource.Replace("<+><&90>", "<+><&90></Image>");

            List<string> list = new List<string>();

            string[] str = Regex.Split(strResource, "<Image>", RegexOptions.IgnoreCase);
            string tmp = "";

            for (int i = 0; i < str.Length; i++)
            {
                tmp = "";
                string[] tmpstr = Regex.Split(str[i], "</Image>", RegexOptions.IgnoreCase);


                if (tmpstr.Length == 1)
                {
                    list.Add(tmpstr[0]);
                }
                else
                {
                    list.Add("<Image>" + tmpstr[0] + "</Image>");
                    tmp = CheckDrawHelp(tmpstr[1]);
                    list.Add(tmp);
                }

            }
            string strReturn = "";

            for (int i = 0; i < list.Count; i++)
            {
                strReturn += list[i];
            }
            return strReturn;
        }

        private string CheckDrawHelp(string strResource)
        {
            if (strResource == "")
            {
                return strResource;
            }
            DataSet gcSet = new DataSet();
            gcSet.ReadXml(Application.StartupPath + "\\XML\\GcInfo.xml");
            int isHave = 0;
            foreach (DataRow row in gcSet.Tables[0].Rows)
            {
                int intTmp = strResource.IndexOf(row["TCM"].ToString().Trim());
                if (intTmp != -1)
                {
                    isHave = 1;
                    break;
                }
            }
            string strTmp = "";
            string strNewValue = strResource;
            if (isHave == 1)
            {
                strNewValue = ReplaceH(strResource, "<H>");
                strNewValue = ReplaceH(strNewValue, "<L>");

                //if (strNewValue.IndexOf("<O>") != -1)
                if (strNewValue == "<%RA>")
                {
                    strNewValue = "<Q></Q>";
                }
                else if (strNewValue.IndexOf("<%RA") == 0)
                {
                    strNewValue = strNewValue.Replace(">", "</R>");
                    strNewValue = strNewValue.Replace("<%RA", "<R>");
                }
                else if (strNewValue.IndexOf("<O>") > 1)
                {
                    strTmp = strNewValue.Replace("<O>", "<Image>φ");
                    int intIndex = 0;
                    for (int j = 0; j < strTmp.Length; j++)
                    {
                        if (strTmp[j] == 'φ')
                        {
                            intIndex = intIndex + 1;
                        }
                    }

                    int intIndexTmp1 = 0;
                    for (int j = 0; j < intIndex; j++)
                    {
                        for (int k = 0; k < strTmp.Length; k++)
                        {
                            if (strTmp[k] == 'φ')
                            {
                                if (intIndexTmp1 != j)
                                {
                                    intIndexTmp1 = intIndexTmp1 + 1;
                                    continue;
                                }

                                string strtmp1 = "";
                                string strtmp2 = "";

                                for (int h = k + 1; h < strTmp.Length; h++)
                                {
                                    if (strTmp[h] == '>')
                                    {
                                        strtmp1 = strTmp.Substring(0, h + 1) + "</Image>";
                                        if (h < strTmp.Length)
                                        {
                                            strtmp2 = strTmp.Substring(h + 1);
                                        }
                                        else
                                        {
                                            strtmp2 = " ";
                                        }
                                        break;
                                    }
                                }
                                if (strtmp1 != "" && strtmp2 != "")
                                {
                                    strTmp = strtmp1 + strtmp2;
                                }
                                else
                                {
                                    strTmp = strtmp1;
                                }
                                break;
                            }
                        }
                    }
                    return strTmp;
                }
                else
                {
                    strNewValue = "<&70><+>" + strNewValue + "<+><&90>";
                }
            }
            else
            {
                if (strNewValue.IndexOf("<T") != -1)
                {

                    return DrawExold(strNewValue, "<T");
                }
            }

            strTmp = strNewValue;
            if (strTmp.IndexOf('<') != -1)
            {
                return "<Image>" + strTmp + "</Image>";
            }
            else
            {
                return strTmp;
            }

        }

        private string CheckDrawXML(string strResource)
        {
            int intIsHave = 0;
            if (strResource.IndexOf("<#C>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#B>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#D>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#E>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#G>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#F>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<#h>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<$t>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<$S>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("S<O>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<J>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<(>") != -1)
            {
                intIsHave = 1;
            }
            else if (strResource.IndexOf("<)>") != -1)
            {
                intIsHave = 1;
            }

            string strReturn = "";
            if (intIsHave == 1)
            {
                strReturn = "<Image><&70><+>" + strResource + "<+><&90></Image>";
            }
            return strReturn;
        }

        /// <summary>
        /// 符合处理扩展
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string DrawExold(string strResource, string code)
        {
            strResource = strResource.Replace(">", "></Image>");
            strResource = strResource.Replace(code, "<Image>" + code);
            return strResource;
        }


        /// <summary>
        /// 符合处理扩展前后追加Image
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string DrawExImage(string strResource, string code, string codelast)
        {
            int tempidx = strResource.IndexOf(code);
            if (tempidx < 0)
                return strResource;
            string strTmp = "";
            string strlast = strResource;
            string strNewValue = "";
            do
            {
                strTmp = strlast.Substring(0, tempidx);
                strlast = strlast.Substring(strTmp.Length);
                strNewValue += strTmp + "<Image>";

                tempidx = strlast.IndexOf(codelast);
                if (tempidx == -1)
                    break;
                strTmp = strlast.Substring(0, tempidx + codelast.Length);
                strNewValue += strTmp + "</Image>";
                strlast = strlast.Substring(strTmp.Length);
                tempidx = strlast.IndexOf(code);
            } while (tempidx > -1);
            strResource = strNewValue + strlast;
            return strResource;
        }
        /// <summary>
        /// 前后替换为<R>
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <param name="codelast"></param>
        /// <returns></returns>
        private string DrawExR(string strResource, string code, string codelast)
        {
            int tempidx = strResource.IndexOf(code);
            if (tempidx < 0)
                return strResource;
            string strTmp = "";
            string strlast = strResource;
            string strNewValue = "";
            do
            {
                strTmp = strlast.Substring(0, tempidx);
                strlast = strlast.Substring(strTmp.Length + code.Length);
                strNewValue += strTmp + "<Image><R>";

                tempidx = strlast.IndexOf(codelast);
                if (tempidx == -1)
                    break;
                strTmp = strlast.Substring(0, tempidx);
                strNewValue += strTmp + "</R></Image>";
                strlast = strlast.Substring(strTmp.Length + codelast.Length);
                tempidx = strlast.IndexOf(code);
            } while (tempidx > -1);
            strResource = strNewValue + strlast;
            return strResource;
        }
        /// <summary>
        /// 前后替换为<H><L>追加Image
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <param name="codelast"></param>
        /// <returns></returns>
        private string DrawExHL(string strResource, string code, string codelast)
        {
            int tempidx = strResource.IndexOf(code);
            if (tempidx < 0)
                return strResource;
            string strTmp = "";
            string strlast = strResource;
            string strNewValue = "";
            do
            {
                strTmp = strlast.Substring(0, tempidx);
                strlast = strlast.Substring(strTmp.Length + code.Length);
                strNewValue += strTmp + "<Image>" + code;

                tempidx = strlast.IndexOf(code);
                if (tempidx == -1)
                    break;
                strTmp = strlast.Substring(0, tempidx + code.Length);
                strNewValue += strTmp.Replace(code, codelast) + "</Image>";
                strlast = strlast.Substring(strTmp.Length);
                tempidx = strlast.IndexOf(code);
            } while (tempidx > -1);
            strResource = strNewValue + strlast;
            return strResource;
        }
        /// <summary>
        /// 符合处理扩展前后追加Image
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string DrawExImageT(string strResource, string code, string codelast)
        {
            int tempidx = strResource.IndexOf(code);
            if (tempidx < 0)
                return strResource;
            string strTmp = "";
            string strlast = strResource;
            string strNewValue = "";
            do
            {
                tempidx = GetnumberIndex(strlast, tempidx);             
                strTmp = strlast.Substring(0, tempidx);
                strlast = strlast.Substring(strTmp.Length);
                strNewValue += strTmp + "<Image>";

                tempidx = strlast.IndexOf(codelast);
                 if (tempidx == -1)
                    break ;

                strTmp = strlast.Substring(0, tempidx + codelast.Length).Replace('Φ', 'φ');
                strNewValue += strTmp + "</Image>";
                strlast = strlast.Substring(strTmp.Length);
                tempidx = strlast.IndexOf(code);
            } while (tempidx > -1);
            strResource = strNewValue + strlast;
            return strResource;
        }
        //公差符号前缀处理
        private int GetnumberIndex(string str, int idx)
        {
            try
            {
                char[] c = str.ToCharArray(0, idx);
                for (int i = idx - 1; i >= 0; i--)
                {
                    ///判断数字及Φ,°,R,SR,M,±
                    if ((c[i] >= 48 && c[i] <= 57) || c[i] == 46 || c[i] == 176 || c[i] == 'Φ' || c[i] == 'R' || c[i] == 'M' || c[i] == 'S' || c[i] == '±')
                    {
                        if (c[i] == 'S' && i != idx - 1)
                        {
                            if (i <= c.Length - 2)
                            {
                                if (c[i + 1] != 'R')
                                    break;
                            }
                            else
                                break;

                        }
                        idx = i;
                    }
                    else
                        break;
                }
            }
            catch (Exception ex)
            {

            }
            return idx;
        }
        /// <summary>
        /// 前后替换为<H><L>追加Image
        /// </summary>
        /// <param name="strResource"></param>
        /// <param name="code"></param>
        /// <param name="codelast"></param>
        /// <returns></returns>
        private string DrawEx(string strResource, string code)
        {
            int tempidx = strResource.IndexOf(code);
            if (tempidx < 0)
                return strResource;
            string strTmp = "";
            string strlast = strResource;
            string strNewValue = "";
            do
            {
                strTmp = strlast.Substring(0, tempidx + code.Length);
                strlast = strlast.Substring(strTmp.Length);
                tempidx += strNewValue.Length;
                int startindex = (strNewValue + strTmp).LastIndexOf("<&70><+>");
                if (startindex >= 0)
                {
                    int endindex = strResource.Substring(startindex).IndexOf("<+><&90>") + startindex;

                    if (startindex <= tempidx && endindex >= tempidx)//包含待处理字串
                    {
                        strNewValue += strTmp;
                    }
                    else
                        strNewValue += strTmp.Replace(code, "<&70><+>" + code + "<+><&90>");
                }
                else
                { 
                    //strNewValue += strTmp.Replace(code, "<&70><+>" + code + "<+><&90>");
                    strNewValue += strTmp.Replace(code, "<Image>" + code + "</Image>");//add:Wangjh 20230301 注释上一句，增加这一句
                }

                tempidx = strlast.IndexOf(code);
            } while (tempidx > -1);
            strResource = strNewValue + strlast;
            return strResource;

        }
        #endregion

        #region 生成Unique标识
        private string _base64corrected = "";
        public string uniqName()
        {
            Byte[] g = Guid.NewGuid().ToByteArray();
            Char[] ret = new Char[32];
            int i = Convert.ToBase64CharArray(g, 0, g.Length, ret, 0);
            _base64corrected = "";
            for (int j = 0; j < ret.Length; j++)
            {
                convBase64((char)ret[j]);
            }
            return _base64corrected;
        }

        private void convBase64(Char c)
        {
            if (c == '/')
            {
                c = '$';
            }
            else if (c == '+')
            {
                c = '#';
            }
            else if (c == '=' || c == '\0')
            {
                return;
            }
            _base64corrected = _base64corrected + c;
        }
        #endregion

        //带H件号替换 yangsj 2018-4-11
        public void ReplaceProductH(XmlDocument myxml, ref string strProductName)
        {
            if (myxml == null)
            {
                myxml = new XmlDocument();
                myxml.Load(m_DataFilePath);
            }
            //获取工艺的零部件号,取掉（H）判断
            XmlNode stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2part_no");

            if (stu != null)
            {
                string strpart_no = stu.InnerText.Trim();
                if (string.IsNullOrWhiteSpace(strpart_no))//此处工艺上零件号推过来的可能为空 add:Wangjh 20180416 
                {
                    Log.SetConfig();//add:Wangjh 2017-9-15 
                    Log.WriteOrcale("PDMTOMES_Assistantclass" + "@^" + "工艺上无零件号" + "@^" + m_DataFilePath + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + GetProductName(m_DataFilePath)[0]);//add:Wangjh 写入数据库    
                    return;
                }

                if (strProductName.Replace(strpart_no, string.Empty).Equals("(H)"))
                {
                    stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2plant");
                    //if (stu.InnerText.Trim().Equals("601"))
                    //    return;
                    //else
                    strProductName = strpart_no;
                }
            }
        }

        /// <summary>
        /// 获取件号
        /// add:Wangjh 20190114
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string[] GetProductName(string fileName)
        {
            string[] result ={"",""};
            XmlDocument myxml = new XmlDocument();
            myxml.Load(fileName);
            //获取件号信息
            XmlNode stu = null;
            stu = myxml.SelectSingleNode("/Root/product/item/ae8_drawingNo");
            if (stu == null)
                stu = myxml.SelectSingleNode("/Root/product/item/ly2drawingNo");
            if (stu == null)
                stu = myxml.SelectSingleNode("/Root/product/item/ly2rough_no");
            if (stu == null)
                return result;
            result[0] = stu.InnerText.Trim();//件号
            stu = myxml.SelectSingleNode("/Root/product/item/item_revision_id");
            result[1] = stu.InnerText.Trim();//版本
            return result;
        }

        /// <summary>
        /// 获取MaterialType
        /// add:Wangjh 20211214
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string GetProductMaterialType(string fileName)
        {
            string result="";
            XmlDocument myxml = new XmlDocument();
            myxml.Load(fileName);
            //获取件号信息
            XmlNode stu = null;
            stu = myxml.SelectSingleNode("/Root/product/item/ae8_materialType");
            if (stu == null)
                stu = myxml.SelectSingleNode("/Root/product/item/ly2rough_type");
            if (stu == null)
                stu = myxml.SelectSingleNode("/Root/ROUGH/ly2rough_type");
            if (stu == null)
                return result;
            result = stu.InnerText.Trim();//MaterialType
            return result;
        }

        /// <summary>
        /// 获取毛料工序node信息
        /// add:Wangjh 
        /// </summary>
        /// <returns></returns>
        public XmlNode GetMLGXNode() {
            //给工艺规程的消耗定额赋值 add:Wangjh 20220422
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            XmlNode stu = myxml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "MEOP")
                    continue;
                if (node.ChildNodes.Count == 0)
                    continue;

                XmlNode specNode = node.SelectSingleNode("MeopType");
                if (specNode.InnerText.Trim() == "毛料工序")
                {
                    return node;
                }
            }
            return null;
        }
        
    }
}
